package eg.edu.eelu.fyp2013.jdetector.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.*;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.border.EmptyBorder;

import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;

import java.awt.*;

import eg.edu.eelu.fyp2013.jdetector.core.filters.impl.AbstractWindowFilter;
import eg.edu.eelu.fyp2013.jdetector.core.filters.impl.ContrastStretching;
import eg.edu.eelu.fyp2013.jdetector.core.filters.impl.HistogramEqualization;
import eg.edu.eelu.fyp2013.jdetector.core.filters.impl.MeanFilter;
import eg.edu.eelu.fyp2013.jdetector.core.filters.impl.MedianFilter;
import eg.edu.eelu.fyp2013.jdetector.core.filters.impl.Segmentation;
import eg.edu.eelu.fyp2013.jdetector.core.swt.Chain;
import eg.edu.eelu.fyp2013.jdetector.core.swt.swtFExtraction;

import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingConstants;


public class ImageFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JSplitPane splitPane;
	private JLabel leftLabel;
	private JLabel rightLabel;
	private BufferedImage sourceImage;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ImageFrame frame = new ImageFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ImageFrame() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1085, 393);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);

		JMenuItem mntmOpen = new JMenuItem("Open");
		
		mntmOpen.addActionListener(new ActionListener() {
			// Open an image file
			final JFileChooser fc = new JFileChooser();
			public void actionPerformed(ActionEvent e) {

				int status = fc.showOpenDialog(null);

				if (status == JFileChooser.APPROVE_OPTION ){
					File selectedFile = fc.getSelectedFile();
					String fileName = selectedFile.getPath();
					//					           JOptionPane.showMessageDialog(null, "You Selected"+fileName);
					try {
						// assign it to a field
						sourceImage = ImageIO.read(new File(fileName));
						// view (display) it
						leftLabel.setIcon(new ImageIcon(sourceImage));
						rightLabel.setIcon(new ImageIcon(sourceImage));
						
					}
					catch (IOException ex) {
						JOptionPane.showMessageDialog(null, ex.getMessage());
					}		
				}
				else if (status == JFileChooser.ERROR_OPTION ){
					JOptionPane.showMessageDialog(null,"Error  :"+ "Please choose an image file" );
				}
				// JOptionPane.showMessageDialog(null, ex.getMessage());


				//TODO enable "Close"
			}
		});
		mnFile.add(mntmOpen);

		JMenuItem mntmSave = new JMenuItem("Save...");
		mntmSave.setEnabled(false);
		mntmSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//TODO Save the image
				//		final JFileChooser fs = new JFileChooser();
				//		int status = fs.showSaveDialog(null);				 
				//		    if (status == JFileChooser.APPROVE_OPTION ){
				//				           File selectedFile = fs.getSelectedFile();
				//			           String fileName = selectedFile.getPath();







				//TODO disable yourself
			}
		});
		mnFile.add(mntmSave);

		final JMenuItem mntmSaveAs =  new JMenuItem("Save As...");
		mntmSaveAs.setEnabled(false);
		mnFile.add(mntmSaveAs);
		mntmSaveAs.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				// get image from imageicon

				Icon icon;
				icon = rightLabel.getIcon();
				Image savedImage = ((ImageIcon) icon).getImage();

				// cast it to bufferedimage
				BufferedImage buffered = (BufferedImage) savedImage;

				try {
					// save to file
					File outputfile = new File("saved.png");

					final JFileChooser fs = new JFileChooser();
					int status = fs.showSaveDialog(null);				 
					if (status == JFileChooser.APPROVE_OPTION ){
						// File selectedFile = fs.getSelectedFile();
						// String fileName = selectedFile.getPath();
						// ImageIO.write((BufferedImage)buffered,"png",new File(fileName));
						// ImageIO.write(buffered, "png", outputfile);
						ImageIO.write(buffered, "png", new File(fs
								.getSelectedFile().getAbsolutePath()
								+ fs.getSelectedFile().getName()+ ".gif"));


					}} catch (IOException e1) {
						e1.printStackTrace();
					}
			}
		}
				);



		////////end of save as







		JMenuItem mntmClose = new JMenuItem("Close");
		mntmClose.setEnabled(false);
		mnFile.add(mntmClose);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mnFile.add(mntmExit);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JToolBar toolBar = new JToolBar();
		contentPane.add(toolBar, BorderLayout.NORTH);

		JButton btnMeanFilter = new JButton("Mean Filter");
		btnMeanFilter.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//TODO ask about filter size
				int filterWidth=7;
				int filterHeight=7;
				// create filter object and apply Filter
				MeanFilter meanFilter = new MeanFilter(filterWidth,filterHeight);
				Image filteredImage = meanFilter.applyFilter(sourceImage);
				// view result
				rightLabel.setIcon(new ImageIcon(filteredImage));
				mntmSaveAs.setEnabled(true);





			}
		});
		toolBar.add(btnMeanFilter);

		JButton btnMedianFilter = new JButton("Median Filter");
		btnMedianFilter.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				int filterWidth=7;
				int filterHeight=7;
				MedianFilter medianFilter = new MedianFilter(filterWidth,filterHeight);
				Image filteredImage = medianFilter.applyFilter(sourceImage);
				rightLabel.setIcon(new ImageIcon(filteredImage));
				mntmSaveAs.setEnabled(true);
				// TODO Auto-generated method stub
			}
		});
		toolBar.add(btnMedianFilter);

		JButton btnContrastStretchingFilter = new JButton("Contrast Stretching Filter");
		btnContrastStretchingFilter.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				ContrastStretching contrastStretchingFilter = new ContrastStretching();
				ArrayList<ContrastStretching.ColorRangeSegmentTransform> segments = new ArrayList<ContrastStretching.ColorRangeSegmentTransform>();
				ContrastStretching.ColorRangeSegmentTransform segment;

				segment= new ContrastStretching.ColorRangeSegmentTransform();
				segment.inputMin = 0;
				segment.inputMax = 59;
				segment.outMin = 0;
				segment.outMax = 149;
				segments.add(segment);

				segment= new ContrastStretching.ColorRangeSegmentTransform();
				segment.inputMin = 60;
				segment.inputMax = 99;
				segment.outMin = 150;
				segment.outMax = 199;
				segments.add(segment);

				segment= new ContrastStretching.ColorRangeSegmentTransform();
				segment.inputMin = 100;
				segment.inputMax = 255;
				segment.outMin = 200;
				segment.outMax = 255;
				segments.add(segment);				

				contrastStretchingFilter.setColorComponentSegments(ContrastStretching.RED, segments);
				contrastStretchingFilter.setColorComponentSegments(ContrastStretching.GREEN, segments);
				contrastStretchingFilter.setColorComponentSegments(ContrastStretching.BLUE, segments);
				Image filteredImage = contrastStretchingFilter.applyFilter(sourceImage);
				rightLabel.setIcon(new ImageIcon(filteredImage));
				mntmSaveAs.setEnabled(true);

			}});
		toolBar.add(btnContrastStretchingFilter);

		JButton btnHistogramEqualization = new JButton("Histogram Equalization");
		btnHistogramEqualization.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				HistogramEqualization histogramEqualization = new HistogramEqualization();
				Image filteredImage = histogramEqualization.applyFilter(sourceImage);
				rightLabel.setIcon(new ImageIcon(filteredImage));
				HistogramFrame frame = new HistogramFrame();
				frame.leftHistogramGraphPanel.setHistogram(histogramEqualization.getHistogramBeforeEqualization());
				frame.rightHistogramGraphPanel.setHistogram(histogramEqualization.getHistogramAfterEqualization());
				frame.setVisible(true);
				mntmSaveAs.setEnabled(true);
			}
		});
		toolBar.add(btnHistogramEqualization);
		
		JButton btnSegmentation = new JButton("Segmentation");
		btnSegmentation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				/////////////
				
					
					// create filter object and apply Filter
					//MeanFilter meanFilter = new MeanFilter(filterWidth,filterHeight);
				Segmentation s = new Segmentation();
					Image filteredImage = s.applySegmentation(sourceImage);
						
					// view result
					rightLabel.setIcon(new ImageIcon(filteredImage));
					mntmSaveAs.setEnabled(true);
				/////////////////////////
			}
		});
		toolBar.add(btnSegmentation);
		
		JButton btnNewButton = new JButton(">Swap<");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Icon icon;
				icon = rightLabel.getIcon();
				sourceImage = (BufferedImage) ((ImageIcon) icon).getImage();
				leftLabel.setIcon(new ImageIcon(sourceImage));
			}
		});
		
		JButton btnChain = new JButton("Chain");
		btnChain.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				BufferedImage OrignalImage;
				
				Icon icon;
				icon = rightLabel.getIcon();
				OrignalImage = (BufferedImage) ((ImageIcon) icon).getImage();
				Chain chinfilter = new Chain();
				
				try {
					BufferedImage ChainImage = null;
					ChainImage = chinfilter.performChain(OrignalImage);
					rightLabel.setIcon(new ImageIcon(ChainImage));
				} catch (MatlabConnectionException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (MatlabInvocationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				
			}
		});
		toolBar.add(btnChain);
		toolBar.add(btnNewButton);
		
		final JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5"}));
		comboBox.setSelectedIndex(2);
		comboBox.setMaximumRowCount(5);


		
		
		
		JButton btnSwt = new JButton("SWT");
		btnSwt.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				BufferedImage fExtractImage;
				Icon icon;
				icon = rightLabel.getIcon();
				fExtractImage = (BufferedImage) ((ImageIcon) icon).getImage();
				swtFExtraction fExtract = new swtFExtraction();
				//try {
					//fExtract.swtExtract(fExtractImage, comboBox.getSelectedIndex()+1);
			//	} catch (MatlabConnectionException e1) {
					// TODO Auto-generated catch block
				//	e1.printStackTrace();
				//} catch (MatlabInvocationException e1) {
					// TODO Auto-generated catch block
					//e1.printStackTrace();
			//	}
			}
		}
		
				);
		toolBar.add(btnSwt);
		toolBar.add(comboBox);
		
		

		splitPane = new JSplitPane();
		contentPane.add(splitPane, BorderLayout.CENTER);


		leftLabel = new JLabel("");
		splitPane.setLeftComponent(leftLabel);


		rightLabel = new JLabel("");
		splitPane.setRightComponent(rightLabel);

		splitPane.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				((JSplitPane)e.getSource()).setDividerLocation(0.5);
			}
			@Override
			public void componentShown(ComponentEvent e) {
				super.componentShown(e);
				((JSplitPane)e.getSource()).setDividerLocation(0.5);
				//				((JSplitPane)e.getSource()).setDividerLocation(((JSplitPane)e.getSource()).getWidth()/2);
			}
		});
		//		splitPane.setDividerLocation(250);
		
		

		
	 rightLabel.addMouseListener(new MouseAdapter(){
	        public void mouseClicked(MouseEvent e) {
	            Point p = e.getPoint();	
	          //showPixel(p);
	            System.out.println(p.x);
	            System.out.println(p.y);
		}});

	}
	
	
    

	/*public BufferedImage getImg() {
	//	return img;
	//}

	public void setImg(BufferedImage img) {
		this.img = img;
	}*/




}
